package zone.czh.woi.woim.protocol.dectector;

import zone.czh.woi.woim.server.channel.protocol.detector.ProtocolDetector;
import zone.czh.woi.woim.server.channel.protocol.initializer.ProtocolInitializer;
/**
*@ClassName: DefaultProtocolDetector
*@Description: None
*@author woi
*/
public class DefaultProtocolDetector extends ProtocolDetector {

    public DefaultProtocolDetector(){
        super(2);
    }

    @Override
    public ProtocolInitializer.Intent detect(byte[] bytes, ProtocolInitializer.Intent latestIntent) {
        ProtocolInitializer.Intent intent = new ProtocolInitializer.Intent();
        if (isHttp(bytes[0],bytes[1])){
            intent.setProtocolName("web_socket");
        }else {
            intent.setProtocolName("protobuf");
        }
        intent.setResetReaderIndex(true);
        intent.setFinished(true);
        return intent;
    }

    private boolean isHttp(int magic1, int magic2) {
        return magic1 == 'G' && magic2 == 'E' || // GET
                magic1 == 'P' && magic2 == 'O' || // POST
                magic1 == 'P' && magic2 == 'U' || // PUT
                magic1 == 'H' && magic2 == 'E' || // HEAD
                magic1 == 'O' && magic2 == 'P' || // OPTIONS
                magic1 == 'P' && magic2 == 'A' || // PATCH
                magic1 == 'D' && magic2 == 'E' || // DELETE
                magic1 == 'T' && magic2 == 'R' || // TRACE
                magic1 == 'C' && magic2 == 'O';   // CONNECT
    }
}
